package com.gitee.feizns.quickstart.demo.rtu;

import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.serial.SerialParameters;
import com.intelligt.modbus.jlibmodbus.serial.SerialPort;
import com.intelligt.modbus.jlibmodbus.serial.SerialUtils;

//@SpringBootApplication
public class ModbusRtuWrite {

    public static void main(String[] args) {
//        SpringApplication.run(ModbusRtuWrite.class, args);
//        System.out.println("hello world");
        connectRtu();
    }

    public static void connectRtu() {
        SerialUtils.setSerialPortFactoryPureJavaComm();
        try {
            SerialParameters params = new SerialParameters();
            params.setDevice("COM8");
            params.setBaudRate(SerialPort.BaudRate.BAUD_RATE_9600);
            params.setDataBits(8);
            params.setStopBits(1);
            params.setParity(SerialPort.Parity.NONE);

            ModbusMaster master = ModbusMasterFactory.createModbusMasterRTU(params);
            master.setResponseTimeout(3000);
//            master.
            master.connect();

            // 执行读写操作
//            master.read

            master.writeSingleRegister(1, 0, 0);

            int[] holdingRegisters = master.readHoldingRegisters(1, 0, 10);
            for (int register : holdingRegisters) {
                System.out.println(register);
            }

            master.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
